package com.hyjiacan.apps.audionly.ui

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.hyjiacan.apps.audionly.R
import com.hyjiacan.apps.audionly.databinding.ActivityExtractProgressBinding
import com.hyjiacan.apps.audionly.ui.viewmodel.ExtractViewModel

/**
 * 提取进度界面Activity
 */
class ExtractProgressActivity : AppCompatActivity() {
    private lateinit var binding: ActivityExtractProgressBinding
    private lateinit var viewModel: ExtractViewModel
    private var taskId: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_extract_progress)

        // 初始化ViewModel
        viewModel = ViewModelProvider(this).get(ExtractViewModel::class.java)
        binding.viewModel = viewModel
        binding.lifecycleOwner = this

        // 从Intent获取参数
        val videoPath = intent.getStringExtra("video_path")
        val audioFormat = intent.getStringExtra("audio_format")
        val audioBitrate = intent.getIntExtra("audio_bitrate", 128)
        val outputFilename = intent.getStringExtra("output_filename")
        val customStoragePath = intent.getStringExtra("custom_storage_path")

        // 开始提取音频
        if (videoPath != null && outputFilename != null && audioFormat != null) {
            taskId = viewModel.startExtract(
                videoPath = videoPath,
                outputFilename = outputFilename,
                bitrate = audioBitrate,
                customStoragePath = customStoragePath,
                format = audioFormat
            )
        }

        // 观察提取状态
        viewModel.extractStatus.observe(this) {
            when (it) {
                ExtractViewModel.Status.COMPLETED -> {
                    // 提取完成，导航到结果界面
                    val resultIntent = Intent(this, ResultActivity::class.java)
                    resultIntent.putExtra("output_path", viewModel.outputFilePath)
                    startActivity(resultIntent)
                    finish()
                }
                ExtractViewModel.Status.FAILED -> {
                    // 提取失败，显示错误信息
                    binding.statusText.text = "提取失败: ${viewModel.errorMessage}"
                }
                else -> {}
            }
        }
    }
}